package com.kgar.util;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.kgar.util.RedisConstants.*;


@Component
@Lazy
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key, Object value, Long time, TimeUnit unit) {
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value), time, unit);
    }

    //设置逻辑过期
    public void setWithLogicExpire(String key, Object value, Long time, TimeUnit unit) {

        //设置过期时间
        RedisData redisData = new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(unit.toSeconds(time)));
        //写入redis
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    //预防缓存穿透
    public <R, ID> R queryWithPassThrough(String keyPrefix, ID id, Class<R> type,
                                          Function<ID, R> dbFallBack,
                                          Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        //如果是空字符串，则返回fail
        if (json != null) {
            return null;
        }

        R r = dbFallBack.apply(id);
        if (r == null) {
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        this.set(key, r, time, unit);
        return r;
    }


    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    //逻辑过期防止缓存击穿(redis中没有就返回null，所以查不到不是热点的key店铺)
    public <R, ID> R queryWithLogicExpire(String keyPrefix, ID id, Class<R> type,
                                          Function<ID, R> dbFallBack,
                                          Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(json)) {
            return null;
        }
        //获取过期时间和店铺信息
        RedisData logicShop = JSONUtil.toBean(json, RedisData.class);
        R r = JSONUtil.toBean((JSONObject) logicShop.getData(), type);
        LocalDateTime expireTime = logicShop.getExpireTime();
        if (expireTime.isAfter(LocalDateTime.now())) {
            //若未过期，直接返回店铺信息
            return r;
        }
        //若已过期，获取互斥锁
        String lockId = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockId);
        if (isLock) {
            //获取到锁，先再从redis中获取信息,双重验证
            String s1 = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isBlank(s1)) {
                return null;
            }
            //获取过期时间和店铺信息
            RedisData logicShop1 = JSONUtil.toBean(json, RedisData.class);
            R r1 = JSONUtil.toBean((JSONObject) logicShop1.getData(), type);
            LocalDateTime expireTime1 = logicShop.getExpireTime();
            if (expireTime1.isAfter(LocalDateTime.now())) {
                //若未过期，直接返回店铺信息
                return r;
            }
            //若缓存中没有，开启线程，重建缓存
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    R r2 = dbFallBack.apply(id);
                    this.setWithLogicExpire(key, r2, time, unit);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    unLock(lockId);
                }
            });
        }

        return r;
    }

    public <R, ID> R queryWithMutex(String keyPrefix, ID id, Class<R> type,
                                    Function<ID, R> dbFallBack,
                                    Long time, TimeUnit unit) {
        String key = keyPrefix + id;
        String json = stringRedisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(json)) {
            return JSONUtil.toBean(json, type);
        }
        //如果是空字符串，则返回fail
        if (json != null) {
            return null;
        }
        //如果缓存未命中，获取锁
        String lock = LOCK_SHOP_KEY + id;
        R r;
        try {
            boolean flag = tryLock(lock);
            if (!flag) {
                Thread.sleep(50);
                return queryWithMutex(keyPrefix, id, type, dbFallBack, time, unit);
            }
            //获取到锁之后，再次检查缓存数据
            String json1 = stringRedisTemplate.opsForValue().get(key);
            if (StrUtil.isNotBlank(json1)) {
                return JSONUtil.toBean(json1, type);
            }
            //如果是空字符串，则返回null
            if (json1 != null) {
                return null;
            }

            //重建数据库
            r = dbFallBack.apply(id);
            Thread.sleep(200);

            if (r == null) {
                stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
            this.set(key, r, time, unit);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lock);
        }
        return r;
    }

    /**
     * 获取锁
     *
     */
    private boolean tryLock(String key) {
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }
}
